package com.spdb.spdbfl.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class HttpRequest {

    /**
     * http post请求application/json
     *
     * @param url
     * @param authToken
     * @param reqParam
     * @return
     */
    public String httpPost(String url, String authToken, String reqParam) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        requestHeaders.set("Auth-Token", authToken);

        HttpEntity httpEntity = new HttpEntity(reqParam, requestHeaders);
//        System.out.println("httpEntity : "+httpEntity);
        ParameterizedTypeReference<String> params = new ParameterizedTypeReference<String>() {
        };
        RestTemplate restTemplate = new RestTemplate();
//        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, params);
            String result = response.getBody();
            System.out.println("接口正常返回: " + result);
            return result;
        } catch (HttpClientErrorException e) {
            String responseBody = e.getResponseBodyAsString();
            System.out.println("接口异常返回：" + JSON.toJSONString(responseBody));
            return e.getMessage();
        }
    }

    /**
     * http post请求multipart/form-data
     *
     * @param url
     * @param map
     * @return
     */
    public String httpPostMultipart(String url, MultiValueMap<String, Object> map) {
//        RestTemplate restTemplate = new RestTemplate(getFactory());
//        restTemplate.setMessageConverters(getConverts());
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
                //只要重写此方法，不去抛出HttpClientErrorException异常即可
                HttpStatus statusCode = clientHttpResponse.getStatusCode();
                System.out.println("错误码 = " + statusCode);
            }
        });
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//        String json = JSON.toJSONString(map);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, headers);
//        ParameterizedTypeReference<MultipartFileDto> params = new ParameterizedTypeReference<MultipartFileDto>() {
//        };

        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(url, httpEntity, String.class);
            String result = response.getBody();
//            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, params);
            System.out.println("接口正常返回: " + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


    public static SimpleClientHttpRequestFactory getFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(10000);
        factory.setReadTimeout(5000);
        return factory;
    }

    public static List<HttpMessageConverter<?>> getConverts() {
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        // String转换器
        StringHttpMessageConverter stringConvert = new StringHttpMessageConverter();
        List<MediaType> stringMediaTypes = new ArrayList<MediaType>() {{
            //添加响应数据格式，不匹配会报401
            add(MediaType.TEXT_PLAIN);
            add(MediaType.TEXT_HTML);
            add(MediaType.APPLICATION_JSON);
            add(MediaType.MULTIPART_FORM_DATA);
        }};
        stringConvert.setSupportedMediaTypes(stringMediaTypes);
        messageConverters.add(stringConvert);
        System.out.println(messageConverters.size());
        return messageConverters;
    }


    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate(getFactory());
        List<HttpMessageConverter<?>> converts = getConverts();
        restTemplate.setMessageConverters(converts);
    }


}


